/*
 *
 *		CREATE SERVER SOCKET IO
 *
 */

module.exports.listen = function(app){

	var server = require('http'),
		serverSocket = server.createServer(app),
		path = require('path'),
		config = require('./config')(),
		parseSignedCookie = require('express/node_modules/connect').utils.parseSignedCookie,
		chat = require('./apps/controllers/c_chat'),
		cookie = require('express/node_modules/cookie'),
		io = require('socket.io').listen(serverSocket);


	serverSocket.listen(config.socketPort);

	io.set('authorization', function (handshakeData, callback) {
		// console.log('-- authorization');
		var _cookie = handshakeData.headers.cookie ? cookie.parse(handshakeData.headers.cookie) : {},
		username = _cookie.username ? parseSignedCookie(_cookie.username, config.CKsecret) : '',
		password = _cookie.password ? parseSignedCookie(_cookie.password, config.CKsecret) : '';
		chat.Authorization(username, password,
			function(err, doc, state){
				if(state){
					handshakeData.idChat = doc.idChat;
					handshakeData._id = doc._id;
				}
				callback(null, state);
			});
	}).on('error', function (reason){
		console.error('Unable to connect Socket.IO', reason);
	}).on('connect_failed', function (reason) {
		console.error('unable to connect to /sockets', reason);
	}).on('connection',function (client){
		// console.log(client.handshake.address.address);
		chat.AddSocketId(client.handshake._id, client.id, undefined);
		console.log('client.id ',client.id);

		client.emit('cns', { message: 'Connect success!' });

		client.on('my other event', function (data) {
		// console.log(data);
		});

		client.on('NewChat', function (targetId){
			client.handshake.targetId = targetId;
			chat.NewChat(client.handshake.idChat, client.handshake.targetId);
		});

		client.on('s_receive', function (data){
			console.log(data);
			chat.NewMessage(client.handshake.idChat,
							data.targetId,
							data.chatId,
							client.handshake.address.address,
							data.time,
							false,
							data.message);

			// data.ownerName =
			chat.GetSocketId(data.targetId, function(arrListSocketId){
				console.log(arrListSocketId);
				for(var i = 0; i < arrListSocketId.length; i++){
					console.log('socket id', arrListSocketId[i]);
					io.sockets.socket(arrListSocketId[i]).emit('c_receive', data);
				}
			});
		});

		client.on('disconnect', function(data){
			console.log(data);
			//client.emit('user disconnected');
			chat.RemoveSocketId(client.handshake._id, client.id, undefined);
			//client.disconnect();
		});
	});

}